package com.employ.admin.common;

import com.employ.admin.exception.CaptchaException;
import com.employ.admin.lang.Const;
import com.employ.admin.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        if ("/login".equals(url) && request.getMethod().equals("POST")){
//校验验证码
            validate(request);
//            如果不正确，就跳转到认证失败的处理器
        }
    }

    //校验验证码逻辑
    protected void validate(HttpServletRequest request){

        String code = request.getParameter("code");
        String key = request.getParameter("token");

        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(key)){
            throw new CaptchaException("验证码错误");
        }

        if (code.equals(redisUtil.hget(Const.CAPTCHA, key))){
            throw new CaptchaException("验证码错误");

        };
//一次性使用
        redisUtil.hdel(Const.CAPTCHA, key);
    }
}
